import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:study_online/entity/Problem.dart';
import 'package:study_online/global/colors.dart';
import 'package:study_online/global/global.dart';

import '../DiscussModel.dart';
import 'ProblemItem.dart';

class DiscussTab extends StatefulWidget {
  DiscussTab({Key key, this.couId, this.type}) : super(key: key);
  int couId, type;

  @override
  _DiscussTabState createState() {
    return _DiscussTabState();
  }
}

class _DiscussTabState extends State<DiscussTab> {
  ProblemList _problemList = new ProblemList([]);

  @override
  void initState() {
    super.initState();
    _loadData();
    // for (int i = 0; i < 5; ++i) {
    //   Problem t = new Problem(
    //       "windChaser",
    //       "1",
    //       "#算法#flutter#回溯法 flutter用起来真舒服",
    //       i,
    //       i,
    //       "2021-10-9",
    //       "https://img2.baidu.com/it/u=172917783,2425047487&fm=26&fmt=auto");
    //   _problemList.data.add(t);
    // }
  }

  void _loadData() async {
    Response response;
    String stuId=Global.getInstance().user.stuId;
    if(widget.type!=2)
     response = await getProblemsByObject(widget.couId, widget.type);
    else
      response = await getProblemsByStuId(widget.couId, stuId);
    print("###" + response.toString());
    var responseData = json.decode(response.toString());
    setState(() {
      _problemList = ProblemList.formJson(responseData);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );
    if (_problemList == null) {
      return Container(
        width: 0,
        height: 0,
      );
    } else {
      return EasyRefresh(
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        header: MaterialHeader(),
        onRefresh: () async {
          _loadData();
        },
        onLoad: () async {
          _loadData();
        },
        child: SingleChildScrollView(
          child: Container(
              color: AppColors.pageBackground,
              child: Column(
                children: _problemList.data
                    .asMap()
                    .keys
                    .map((index) => ProblemItem(
                          problem: _problemList.data[index],
                        ))
                    .toList(),
              )),
        ),
      );
    }
  }
}
